package cn.ec.singleton;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

import java.io.IOException;

/**
 * 单例模式,获取JackJson的ObjectMapper实例
 */
public enum JsonMapper {
    /**
     * 实例
     */
    INSTANCE;
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule());
    }

    public ObjectMapper getObjectMapper() {
        return mapper;
    }

    /**
     * 序列化
     * @param o 类实例
     * @return json字符串
     * @throws JsonProcessingException x
     */
    public String serialize(Object o) throws JsonProcessingException {
        return INSTANCE.getObjectMapper().writeValueAsString(o);
    }

    /**
     * 反序列化-暂时用不到
     * @param json 字符串
     * @param clazz 类型
     * @return 反序列化后的实例
     * @throws IOException x
     */
    public Object deSerialize(String json, Class clazz) throws IOException {
        return INSTANCE.getObjectMapper().readValue(json, clazz);
    }

}